package com.instagram.instadownloader;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;

import com.instagram.instadownloader.bookmark.BookmarksManager;
import com.instagram.instadownloader.bookmark.OnAddBookmarkListener;
import com.instagram.instadownloader.history.HistoryManager;
import com.instagram.instadownloader.history.HistoryObject;
import com.instagram.instadownloader.utils.IDefines;
import com.instagram.instadownloader.utils.SharedPrefs;
import com.instagram.instadownloader.utils.download.InstaDownloadManager;

/**
 * The Class BaseInstaDownloaderActivity.
 * @author HuanND
 */
public abstract class BaseInstaDownloaderActivity extends BaseSlidingFragmentActivity{

	/** The m insta download manager. */
	protected InstaDownloadManager mInstaDownloadManager;
	
	/** The m listener. */
	private	  OnDownloadCompleteListener mListener;
	
	private String shareInstaUrl="";
	private String curFileName = "";
	
	public void setShareInstaUrl (String url){
		shareInstaUrl=url;
	}
	public String getShareUrl() {
        return shareInstaUrl;
    }
	
	private String urlImage = "";
	public void setUrlImage(String urlimg) {
		urlImage = urlimg;
	}
	
	public String getCurrentFileName() {
		return curFileName;
	}
	
	public void setCurrentFIleName(String pName) {
		this.curFileName= pName;
	}
	
	/* (non-Javadoc)
	 * @see com.instagram.instadownloader.BaseSlidingFragmentActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle arg0) {
		mInstaDownloadManager = new InstaDownloadManager(this);
		super.onCreate(arg0);
	}
	
	/**
	 * Gets the insta download manager.
	 *
	 * @return the insta download manager
	 */
	public InstaDownloadManager getInstaDownloadManager(){
		return mInstaDownloadManager;
	}
	
//	/** The m receiver. */
//	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
//		
//		@Override
//		public void onReceive(Context context, Intent intent) {
////			HistoryObject object = new HistoryObject(intent.getData(), shareInstaUrl);
//			
//			if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
//				long receivedID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
//		        DownloadManager mgr = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
//		 
//		        DownloadManager.Query query = new DownloadManager.Query();
//		        query.setFilterById(receivedID);
//		        Cursor cur = mgr.query(query);
//		        int index = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
//		   
//		        if(cur.moveToFirst()) {
//		            if(cur.getInt(index) == DownloadManager.STATUS_SUCCESSFUL){
//		                // do something
//		            	String pathResult = "";
//		                if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES. HONEYCOMB ){
//		                	 int nameIndex = cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
//		                	 pathResult = cur.getString(nameIndex);
//				            	
//				        }else{
//				        	pathResult = getCurrentFileName();
//				        }
//		                
//		                HistoryManager.getInstance().addHistory(new HistoryObject(pathResult, shareInstaUrl, urlImage));
//		                BookmarksManager.getInstance().updatePath(shareInstaUrl, pathResult);
//		            	SharedPrefs.getInstance().setDefaultPath(pathResult);
//		            	
//		            	if(mListener!=null){
//		    				mListener.onDownloadComplete(intent);
//		    			}
//		            }
//		        }
//		        cur.close();
//			}
//		
//		}
//	};
	
	public void onDownloadSucess(String absolutePath){
		HistoryManager.getInstance().addHistory(new HistoryObject(absolutePath, shareInstaUrl, urlImage));
        BookmarksManager.getInstance().updatePath(shareInstaUrl, absolutePath);
    	SharedPrefs.getInstance().setDefaultPath(absolutePath);
    	setCurrentFIleName(absolutePath);
    	if(mListener!=null){
			mListener.onDownloadComplete(null);
		}
	}
	
	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onResume()
	 */
	protected void onResume() {
		super.onResume();
//		IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
//		  registerReceiver(mReceiver, intentFilter);
//		LocalBroadcastManager.getInstance(this).registerReceiver(localReceiver, new IntentFilter(IDefines.LOCAL_FILLTER));  
	}
	
	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
//		unregisterReceiver(mReceiver);
//		LocalBroadcastManager.getInstance(this).unregisterReceiver(localReceiver);
	}
	
	/**
	 * Sets the on download complete listener.
	 *
	 * @param listener the new on download complete listener
	 */
	public void setOnDownloadCompleteListener(OnDownloadCompleteListener listener){
		mListener = listener;
	}
	
	/**
	 * The listener interface for receiving onDownloadComplete events.
	 * The class that is interested in processing a onDownloadComplete
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addOnDownloadCompleteListener<code> method. When
	 * the onDownloadComplete event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see OnDownloadCompleteEvent
	 */
	public interface OnDownloadCompleteListener{
		
		/**
		 * On download complete.
		 *
		 * @param intent the intent
		 */
		public void onDownloadComplete(Intent intent);
	}
	
	BroadcastReceiver localReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals("INSTA_DOWNLOAD_BROADCAST")){
				int ac = intent.getIntExtra(IDefines.LOCAL_ACTION, -1);
				if(ac == IDefines.AC_ADD_BOOKMARK){
					if(mAddBookmarkListener != null){
						mAddBookmarkListener.onAddNewBookmark();
					}
				}
			}
		}
	};
	
	private OnAddBookmarkListener mAddBookmarkListener;
	public void setAddBookmarkListener(OnAddBookmarkListener pAddBookmarkListener) {
		this.mAddBookmarkListener = pAddBookmarkListener;
	}
	
	public void sendLocalBroadcast(int pAction) {
		Intent i = new Intent(IDefines.LOCAL_FILLTER);
		i.putExtra(IDefines.LOCAL_ACTION, pAction);
		LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
	}
}
